package gc3d.servlet;

import gc3d.database.DBSettings;
import gc3d.database.GridPovDB;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;


public class nodeUpdate extends HttpServlet{

	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException {
		PrintWriter out = res.getWriter();
		GridPovDB db;
		//out.print("toepie");
		
		try {
			db = new GridPovDB(DBSettings.getDBURL(),DBSettings.getDBuser(),DBSettings.getDBpass());
			//ResultSet rs = db.query("SELECT task_id from tasks;");
		    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd H:mm:ss");
			ResultSet rs = db.query("select nodes.node_id, nodes.start_time, nodes.last_update, nodes.status, count(jobs.node_id) as jobs from jobs,nodes where jobs.node_id = nodes.node_id group by nodes.node_id, nodes.start_time, nodes.last_update, nodes.status order by nodes.last_update desc");
			JSONArray nodeList = new JSONArray(); 
			while( rs.next() ){
			
				JSONObject node = new JSONObject();

				
				
				node.put("id",rs.getString("node_id"));
				node.put("start_time",sdf.format(rs.getTimestamp("start_time").getTime()));
				node.put("last_update",sdf.format(rs.getTimestamp("last_update").getTime()));
				node.put("status",rs.getString("status"));
				node.put("jobs",rs.getString("jobs"));
				
				nodeList.add(node);
				
				
			}
			out.print(nodeList);
		} catch (ClassNotFoundException e1) {
			out.println("ClassNotFoundExceptio");
			// TODO Auto-generated catch block
			out.println(e1.getMessage());
		} catch (SQLException e1) {
			out.println("SQLException");
			// TODO Auto-generated catch block
			out.println(e1.getMessage());
		}
	}
}
